package com.example.util;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;

public class HttpRequest {
    public static String sendGet(String url, String headers, boolean ignoreCert) throws Exception {
        return sendRequest("GET", url, headers, null, ignoreCert);
    }

    public static String sendPost(String url, String headers, String data, boolean ignoreCert) throws Exception {
        return sendRequest("POST", url, headers, data, ignoreCert);
    }

    private static String sendRequest(String method, String url, String headers, String data, boolean ignoreCert) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

        if (ignoreCert && connection instanceof HttpsURLConnection) {
            SSLContext sc = SSLContext.getInstance("SSL");
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() { return null; }
                public void checkClientTrusted(X509Certificate[] certs, String authType) { }
                public void checkServerTrusted(X509Certificate[] certs, String authType) { }
            }};
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
            ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) { return true; }
            });
        }

        connection.setRequestMethod(method);
        connection.setDoOutput(true);

        // Set headers
        if (headers != null && !headers.isEmpty()) {
            String[] headerPairs = headers.split(";");
            for (String pair : headerPairs) {
                String[] keyValue = pair.split(":");
                connection.setRequestProperty(keyValue[0].trim(), keyValue[1].trim());
            }
        }

        // Send request data
        if (data != null && !data.isEmpty()) {
            OutputStream os = connection.getOutputStream();
            os.write(data.getBytes());
            os.flush();
            os.close();
        }

        int responseCode = connection.getResponseCode();
        LogUtil.logInfo("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }
}


